package com.adams.common;

import java.io.File;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.adams.utils.AppContext;
import com.adams.utils.SystemConfig;

public class SystemStartup implements ServletContextListener {

	private static final Logger log = LoggerFactory
			.getLogger(SystemStartup.class);

	@Override
	public void contextInitialized(ServletContextEvent event) {
		ApplicationContext context = WebApplicationContextUtils
				.getWebApplicationContext(event.getServletContext());

		AppContext.setContext(context);
		
		this.initSystemConfigInfo();
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub

	}

	/**
	 * 
	 * Description : 初始化 SystemConfig配置文件信息 动态创建 配置的 物理目录
	 * 
	 */
	private void initSystemConfigInfo() {

		String directorys = null;
		try {
			directorys = SystemConfig.getInstance().getString(
					"adams.init.file.directory");
			
			log.info("adams.init.file.directory : " + directorys);
			
			if (StringUtils.isNotEmpty(directorys)) {
				for (String directory : directorys.split(";")) {

					String dir = SystemConfig.getInstance()
							.getString(directory);
					if (StringUtils.isNotEmpty(dir)) {
						File file = new File(dir);
						if (file.exists() == false) {
							file.mkdirs();
							log.info("directory is not exists : " + dir);
							log.info("directory create : " + dir);
						}
					}
					
					log.info("directory alrealdy exists : " + dir);
				}
			}
		} catch (Exception e) {
			log.error("create directory error");
			log.error("adams.init.file.directory : " + directorys);
			log.error(e.getMessage(), e);
		}
	}
}
